# -*- coding: utf-8 -*-

'''
Created on April 22, 2017
kNN: k Nearest Neighbors
'''

import numpy
import operator

def getDistance(inX, dataSet):
    '''
    计算输入向量X与每个目标向量的距离(向量的距离公式)
    '''
    dataSetSize = dataSet.shape[0]
    diffMat = numpy.tile(inX, (dataSetSize, 1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis=1)
    return sqDistances ** 0.5

def classify0(inX, dataSet, labels, k):
    '''
    计算输入向量X与每个目标向量的距离
    '''
    distances = getDistance(inX, dataSet)
    '''
    排序
    '''
    sortedDistIndicies = distances.argsort()
    classCount = {}
    for i in range(k):
        '''
        计算出现的频次(概率)
        '''
        voteIlabel = labels[sortedDistIndicies[i]]
        classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1

    '''
    开始排序
    '''
    sortedClassCount = sorted(classCount.iteritems(),
        key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def testClassify0():
    input = [1, 3]
    group = numpy.array([[1,1],[4,5],[0,1]])
    labels = ['A', 'B', 'A']
    result = classify0(input, group, labels, 3)
    print('input: {}, result: {}' . format(input, result))

'''
dating data
'''
def file2Matrix(filename):
    fr = open(filename)
    arrayOlines = fr.readlines()
    numberOfLines = len(arrayOlines)
    returnMat = numpy.zeros((numberOfLines, 3))
    classLabelVect = []

    index = 0
    for line in arrayOlines:
        line = line.strip()
        listFromLine = line.split('\t')
        returnMat[index,:] = listFromLine[0:3]
        classLabelVect.append(int(listFromLine[-1]))
        index += 1

    return returnMat, classLabelVect

